package app.itgungnir.compose.wan.business.main.agenda

import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.NoAccounts
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import app.itgungnir.compose.wan.Routes
import app.itgungnir.compose.wan.WanApp
import app.itgungnir.compose.wan.utils.dataStore
import app.itgungnir.compose.wan.utils.decode
import app.itgungnir.compose.wan.widgets.*
import kotlinx.coroutines.flow.map

@Composable
fun AgendaScreen(navController: NavController = rememberNavController(), activity: AppCompatActivity) {
    val viewModel = viewModel<AgendaViewModel>()
    val dialogState = remember { mutableStateOf(false) }
    val agendaState = remember { mutableStateOf<Agenda?>(null) }
    val hasLoginState = WanApp.instance.dataStore.data.map { it.hasLogin }.collectAsState(initial = false)
    // UI
    WanScaffold(
        title = "我的待办",
        canGoBack = false,
        loadingState = viewModel.loadingState.collectAsState(),
        loadingJob = viewModel.loadingJob,
        errorState = viewModel.errorState.collectAsState(initial = null),
        floatingActionButton = {
            if (hasLoginState.value) {
                WanFab(icon = Icons.Filled.Add) {
                    viewModel.dismissDialogState.value = false
                    agendaState.value = null
                    dialogState.value = true
                }
            }
        }
    ) {
        if (hasLoginState.value) {
            AgendaListScreen(viewModel = viewModel, dialogState = dialogState, agendaState = agendaState)
        } else {
            ErrorPage(icon = Icons.Filled.NoAccounts, title = "您还没有登录，不能使用此功能", buttonText = "去登录") {
                navController.navigate(route = Routes.LOGIN)
            }
        }
    }
    AgendaDialog(activity = activity, dialogState = dialogState, agendaState = agendaState, viewModel = viewModel)
}

@Composable
private fun AgendaListScreen(
    viewModel: AgendaViewModel = viewModel(),
    dialogState: MutableState<Boolean> = mutableStateOf(false),
    agendaState: MutableState<Agenda?> = mutableStateOf(null)
) {
    val agendaPagingSource = viewModel.agendaListFlow.collectAsLazyPagingItems()
    Column(modifier = Modifier.fillMaxWidth()) {
        Surface(modifier = Modifier.zIndex(2F), elevation = 2.dp) {
            AgendaFilter(
                statusValueState = viewModel.statusState,
                typeValueState = viewModel.typeState,
                priorityValueState = viewModel.priorityState,
                orderByValueState = viewModel.orderByState,
                onConditionChanged = { agendaPagingSource.refresh() }
            )
        }
        WanPagingList(pagingItems = agendaPagingSource) {
            items(agendaPagingSource) { agenda ->
                AgendaItem(
                    item = agenda?.copy(title = agenda.title?.decode(), content = agenda.content?.decode()),
                    editCallback = {
                        viewModel.dismissDialogState.value = false
                        agendaState.value = it
                        dialogState.value = true
                    },
                    deleteCallback = {
                        viewModel.deleteAgenda(it.id)
                    },
                    toggleCallback = {
                        viewModel.updateAgendaStatus(it)
                    }
                )
            }
        }
    }
}

@Composable
private fun AgendaDialog(
    activity: AppCompatActivity,
    dialogState: MutableState<Boolean>,
    agendaState: MutableState<Agenda?>,
    viewModel: AgendaViewModel = viewModel()
) {
    WanDialog(
        state = dialogState,
        loadingJob = viewModel.dialogLoadingJob,
        dismissState = viewModel.dismissDialogState.collectAsState(),
        errorState = viewModel.dialogErrorState.collectAsState(initial = null),
        paddingValues = PaddingValues(horizontal = 20.dp, vertical = 15.dp)
    ) {
        val originData = agendaState.value
        AgendaDialogUI(
            activity = activity,
            origin = originData,
            loadingState = viewModel.dialogLoadingState.collectAsState(),
            errorState = viewModel.dialogErrorState.collectAsState(initial = null)
        ) { title, content, date, priority, type ->
            when (originData) {
                null -> viewModel.addAgenda(title, content, date, type, priority)
                else -> viewModel.updateAgenda(
                    originData.copy(
                        title = title,
                        content = content,
                        dateStr = date,
                        priority = priority ?: 2,
                        type = type ?: 1
                    )
                )
            }
        }
    }
}
